const express = require("express")
const User = require('../mod/user')
const register = express.Router() //创建路由

const Mail = require("../tool/mail.js")
var {
    setCrypto
} = require('../tool/crypto.js')
const Rank = require("../mod/rank")


//注册新用户
register.post("/", async (req, res) => {

    let {
        username,
        email,
        password,
        checkPass
    } = req.body
    if (password !== checkPass) {
        res.json({
            message: "密码不一致",
            code:201
        })
        return
    }

    //具体使用，注意在登陆时也需要对传入的数据进行一次加密，再比较
    password = setCrypto(password)
    req.body.password = password
    let time1 = Date.now()   //获取提交验证码时的时间
    let obj = JSON.parse(process.env.code)
    let olduser = await User.findOne({
        email
    })
    if (req.body.yzmval != obj.code1) {
        return res.json({
            message: "验证码错误",
            code:202
        })
    }
    if (time1 - obj.time >= 1000 * 60 * 5) {      

        return res.json({
            message: "验证码已经失效",
            code:201
        })

    }
    if (olduser) {
        return res.status(203).json({
            message: "用户已经存在,注意邮箱的唯一性。如已注册，可以找回密码",
            code:203
        })
    }

    //将用户状态改成使用状态
    req.body.isExistence=true
    let newuser = await new User(req.body).save()
    res.json({
        data: newuser,
        message: "注册成功",
        code:200
    })
})


//定义的一个处理产生4位数的随机yzm

function computedCodenum(oldnum) {
    let len = oldnum.length

    switch (len) {
        case 1:
            return `000${oldnum}`;
            break;
        case 2:
            return `00${oldnum}`;
            break;
        case 3:
            return `0${oldnum}`;
            break;
        case 4:
            return `${oldnum}`;
            break;
    }


}

//发送邮箱验证码
register.get("/postmail", async (req, res) => {
    let {
        email
    } = req.query

    let codeNum = parseInt(Math.random() * 10000) + ''


    //将codeNum弄成合适的形式
    codeNum = computedCodenum(codeNum)

    let data = await Mail.sendmail(email, codeNum)
    let time = Date.now()       //记录发送邮箱时的时间
  
    if (data) {
        process.env.code = JSON.stringify({
            code1: codeNum,
            time: time
        })
        return res.json({
            message: "发送成功",
            code: 200
        })
    }

    res.json({
        message: "发送邮箱失败,请检查邮箱号后重新获取",
        code:201
    })

})



module.exports = register